package com.ruoyi.system.netty;

import cn.hutool.core.io.BufferUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.socket.nio.NioClient;

import java.nio.ByteBuffer;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class Client2 {
    public static void main(String[] args) {
        NioClient client = new NioClient("127.0.0.1", 8888);
        client.setChannelHandler((sc)->{
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            //从channel读数据到缓冲区
            int readBytes = sc.read(readBuffer);
            if (readBytes > 0) {
                //Flips this buffer.  The limit is set to the current position and then
                // the position is set to zero，就是表示要从起始位置开始读取数据
                readBuffer.flip();
                //returns the number of elements between the current position and the  limit.
                // 要读取的字节长度
                byte[] bytes = new byte[readBuffer.remaining()];
                //将缓冲区的数据读到bytes数组
                readBuffer.get(bytes);
                String body = StrUtil.utf8Str(bytes);
                Console.log("[{}]: {}", sc.getRemoteAddress(), body);
            } else if (readBytes < 0) {
                sc.close();
            }
        });
        client.listen();
        boolean i=true;
        while (true) {
            if(i){
                client.write(BufferUtil.createUtf8("LNG = 117.15618134, LAT = 34.15148926, TIME = 2022-02-22 11:02:58"));
            }else{
                String res = "feaa0101010101010101010101010d0a";
                byte[] bytes1 = HexUtil.decodeHex(res);
                client.write(BufferUtil.create(bytes1));
            }
            i=!i;
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

